//
//  NYAlertView.m
//  Nooryes
//
//  Created by uuu9 on 2017/3/9.
//  Copyright © 2017年 Jason. All rights reserved.
//

#import "NYAlertView.h"
#import "NSString+dynamicSize.h"
static NYAlertView *_shardAlert = nil;

@interface NYAlertView()

@property (nonatomic, strong) UILabel *label;

@end

@implementation NYAlertView

+ (instancetype)sharedAlertView{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!_shardAlert) {
            _shardAlert = [[self alloc] init];
        }
    });
    return _shardAlert;
}


- (instancetype)init{
    if (self = [super init]) {
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        self.backgroundColor = [UIColor clearColor];
        self.bounds = CGRectMake(0, 0, kScreenWidth, 50);
        self.center = delegate.window.center;
        [self addSubViews];
        [delegate.window addSubview:self];
        //        [[[[UIApplication sharedApplication] windows] lastObject] addSubview:self];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAlert)];
        [self addGestureRecognizer:tapGesture];
    }
    return self;
}


- (void)addSubViews{
    UILabel *label = [[UILabel alloc] init];
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = 5;
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = UIColorFromRGB(kAllWhiteColor);
    label.backgroundColor = UIColorFromRGB(0x000000);
    _label = label;
    [self addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
    }];
    
}

- (void)setTitle:(NSString *)title{
    _title = title;
    _label.text = title;
 
    [self.label layoutIfNeeded];
  
    
}
-(void)layoutSubviews{
    [super layoutSubviews];
    float width = ceil([_title dynamicWidthWithFontSize:14 andCGSize:CGSizeMake(MAXFLOAT, 16) andLineSpace:0].width);
     if (width > kScreenWidth - 80) {
         width = kScreenWidth - 80;
     }
     width = width +30;
     self.label.bounds = CGRectMake(0, 0, width,50);

    
}

- (void)showAlert:(AlertBlock)block{
    [UIView animateWithDuration:0.25 animations:^{
        self.hidden = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissAlert:block];
        });
    }];
}


- (void)dismissAlert:(AlertBlock)block{
    [UIView animateWithDuration:0.15 animations:^{
        block();
        [self dismissAlert];
    }];
}

- (void)dismissAlert{
    self.hidden = YES;
}


@end
